package com.itjin.health.controller;

import com.itjin.health.common.BaseResponse;
import com.itjin.health.common.ResultUtils;
import com.itjin.health.domain.dto.ForgetPasswordStep1Request;
import com.itjin.health.domain.dto.ForgetPasswordStep2Request;
import com.itjin.health.domain.dto.UserLoginRequest;
import com.itjin.health.domain.dto.UserRegisterRequest;
import com.itjin.health.domain.dto.UserUpdateInfoRequest;
import com.itjin.health.domain.vo.UserComprehensiveInfoVO;
import com.itjin.health.domain.vo.UserStatsVO;
import com.itjin.health.domain.vo.UserVO;
import com.itjin.health.exception.BusinessException;
import com.itjin.health.exception.ErrorCode;
import com.itjin.health.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
@Slf4j
public class UserController {

  @Resource
  private UserService userService;

  /**
   * 用户注册
   *
   * @param userRegisterRequest 用户注册请求
   * @return 注册结果
   */
  @PostMapping("/register")
  @ApiOperation(value = "用户注册")
  public BaseResponse<Integer> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
    if (userRegisterRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    Integer userId = userService.userRegister(userRegisterRequest);
    return ResultUtils.success(userId);
  }

  /**
   * 用户登录
   *
   * @param userLoginRequest 用户登录请求
   * @param request          HTTP请求
   * @return 登录结果
   */
  @PostMapping("/login")
  @ApiOperation(value = "用户登录")
  public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
    if (userLoginRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    UserVO userVO = userService.userLogin(userLoginRequest);
    // 记录用户的登录态
    request.getSession().setAttribute("userId", userVO.getId());
    request.getSession().setAttribute("userRole", userVO.getRole());
    return ResultUtils.success(userVO);
  }

  /**
   * 用户注销
   *
   * @param request HTTP请求
   * @return 注销结果
   */
  @PostMapping("/logout")
  @ApiOperation(value = "用户退出登录")
  public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
    if (request == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    request.getSession().removeAttribute("userId");
    return ResultUtils.success(true);
  }

  /**
   * 获取当前登录用户
   *
   * @param request HTTP请求
   * @return 当前登录用户
   */
  @GetMapping("/current")
  @ApiOperation(value = "获取当前登录用户")
  public BaseResponse<UserVO> getCurrentUser(HttpServletRequest request) {
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;
    UserVO userVO = userService.getLoginUser(userId);
    return ResultUtils.success(userVO);
  }

  /**
   * 获取当前用户统计信息
   *
   * @param request HTTP请求
   * @return 用户统计信息
   */
  @GetMapping("/status")
  @ApiOperation(value = "获取当前用户统计信息")
  public BaseResponse<UserStatsVO> getUserStats(HttpServletRequest request) {
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;
    UserStatsVO userStatsVO = userService.getUserStats(userId);
    return ResultUtils.success(userStatsVO);
  }

  /**
   * 验证邮箱验证码
   *
   * @param email   邮箱
   * @param captcha 验证码
   * @return 验证结果
   */
  @GetMapping("/verify-captcha")
  @ApiOperation(value = "验证邮箱验证码")
  public BaseResponse<Boolean> verifyCaptcha(@RequestParam String email, @RequestParam String captcha) {
    boolean result = userService.verifyCaptcha(email, captcha);
    return ResultUtils.success(result);
  }

  /**
   * 忘记密码第一步：验证身份
   *
   * @param request 忘记密码第一步请求
   * @return 重置令牌
   */
  @PostMapping("/forget-password/step1")
  @ApiOperation(value = "忘记密码第一步：验证身份")
  public BaseResponse<String> forgetPasswordStep1(@RequestBody ForgetPasswordStep1Request request) {
    if (request == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    String resetToken = userService.forgetPasswordStep1(request);
    return ResultUtils.success(resetToken);
  }

  /**
   * 忘记密码第二步：重置密码
   *
   * @param request 忘记密码第二步请求
   * @return 重置结果
   */
  @PostMapping("/forget-password/step2")
  @ApiOperation(value = "忘记密码第二步：重置密码")
  public BaseResponse<Boolean> forgetPasswordStep2(@RequestBody ForgetPasswordStep2Request request) {
    if (request == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    boolean result = userService.forgetPasswordStep2(request);
    return ResultUtils.success(result);
  }

  /**
   * 获取用户全面信息
   * 
   * @param userId  用户ID（可选，不传则获取当前登录用户信息）
   * @param request HTTP请求
   * @return 用户全面信息
   */
  @GetMapping("/comprehensive-info")
  @ApiOperation(value = "获取用户全面信息", notes = "包含基本信息、伤病报告数量、康复计划等全部相关信息")
  public BaseResponse<UserComprehensiveInfoVO> getUserComprehensiveInfo(
      @ApiParam(value = "用户ID（不传则获取当前登录用户）") @RequestParam(required = false) Integer userId,
      HttpServletRequest request) {
    // 获取当前登录用户ID
    Object currentUserIdObj = request.getSession().getAttribute("userId");
    if (currentUserIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    // 如果未指定userId，则使用当前登录用户ID
    Integer targetUserId = userId != null ? userId : (Integer) currentUserIdObj;

    // 获取角色，如果不是管理员且查询的不是自己，则无权限
    String userRole = (String) request.getSession().getAttribute("userRole");
    Integer currentUserId = (Integer) currentUserIdObj;
    if (!"管理员".equals(userRole) && !"超级管理员".equals(userRole) && !currentUserId.equals(targetUserId)) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权查看其他用户信息");
    }

    UserComprehensiveInfoVO userInfo = userService.getUserComprehensiveInfo(targetUserId);
    return ResultUtils.success(userInfo);
  }

  /**
   * 更新用户信息
   * 
   * @param updateInfoRequest 用户信息更新请求
   * @param request           HTTP请求
   * @return 更新结果
   */
  @PostMapping("/update-info")
  @ApiOperation(value = "更新用户信息", notes = "用户可更新自己的用户名、邮箱、手机号和密码")
  public BaseResponse<Boolean> updateUserInfo(@RequestBody UserUpdateInfoRequest updateInfoRequest,
      HttpServletRequest request) {
    // 检查用户是否登录
    Object userIdObj = request.getSession().getAttribute("userId");
    if (userIdObj == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Integer userId = (Integer) userIdObj;

    // 调用服务更新用户信息
    boolean result = userService.updateUserInfo(userId, updateInfoRequest);
    return ResultUtils.success(result);
  }
}
